<?php
    include_once("../action/checkAuthenticationAction.php");
    include_once("../service/productService.php");
    include_once("../service/categoryService.php");
    include_once("../util/constant.php");
    include_once("../util/message.php");
	include_once("../util/functionUtil.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Chi tiết khuyến mãi</title>
	<?php 
        include("import-css.php");
        include("import-css-upload.php");
    ?>
</head>
<body>
    <?php include("header.php");?>
    
	<div class="container-fluid">
		<div class="row-fluid">
            <?php include_once("menu.php");?>
			<div id="content" class="span10">
            	<?php
                    $class = null;
                    $message = null;
                    
                    if(isset($_GET["action"])){
                        $action = $_GET["action"];
                        
                        if($action == INSERT_FAILED){
                            $message = $messages["createDiscoutFailed"];
                            $class = FAILED_MESSAGE_CLASS;
                        } else if($action == INSERT_SUCCESSFULLY){
                            $message = $messages["createDiscoutSuccessfully"];
                            $class = SUCCESSFULL_MESSAGE_CLASS;
                        } else if($action == UPDATE_SUCCESSFULLY){
                            $message = $messages["editDiscoutSuccessfully"];
                            $class = FAILED_MESSAGE_CLASS;
                        } else if($action == INSERT_FAILED){
                            $message = $messages["editDiscoutFailed"];
                            $class = FAILED_MESSAGE_CLASS;
                        }
						
						if(isset($class)){
				?>
                			<div id="msg" class="center alert <?php showClass($class);?>"><?php showMessage($message);?></div>
                <?php
						}
                    }
                ?>
                
            	<div class="box">
                	<div class="box-content">
                    	<?php
							if(!authUtil(array("edit promotion","create promotion","view promotion"),$perm_array,false)){
								echo "<script>window.location.href='../admin/index.php';</script>";
							}
							
						?>
                    	<form id="fileupload" method="post" enctype="multipart/form-data" class="form-horizontal">
                        	<?php
								$disId = 0;
								$isEditMode = false;
								$_SESSION["uploadMode"] = UPLOAD_MODE_DISCOUNT;
								unset($_SESSION["disId"]);
                                $_SESSION["newAction"] = "1";
								
								if(isset($_GET["id"])){
									$disId = $_GET["id"];
									$_SESSION["disId"] = $_GET["id"];
                                    unset($_SESSION["newAction"]); 
									$isEditMode = true;
									$discountInfo = findDiscountBy($disId);
								}
                            ?>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Tên</label>
                                <div class="controls">
                                    <input type="text" name="name" class="input-xlarge focused" value="<?php if($isEditMode) echo $discountInfo["DIS_NAME"];?>">
                                </div>    
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Giá trị</label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input type="text" name="value" class="input-xlarge focused" value="<?php if($isEditMode) echo $discountInfo["DIS_VALUE"] * 100;?>"><span class="add-on">%</span>
                                    </div>
                                </div>    
                            </div>
                            <?php
                                if($isEditMode){
                            ?>
                            <div class="control-group">
                                <label class="control-label" for="textarea2">Hình ảnh <br/>(Kích thước: 56 x 56)</label>
                                <div class="controls">
                                    <div class="row fileupload-buttonbar" style="margin: 3px;">
                                        <div class="col-lg-7">
                                            <!-- The fileinput-button span is used to style the file input field as button -->
                                            <span class="btn btn-success fileinput-button">
                                                <i class="glyphicon glyphicon-plus"></i>
                                                <span>Thêm hình</span>
                                                <input type="file" name="files[]">
                                            </span>
                                            <button type="submit" class="btn btn-primary start">
                                                <i class="glyphicon glyphicon-upload"></i>
                                                <span>Tải hình</span>
                                            </button>
                                            <button type="button" class="btn btn-danger delete" onClick="deleteImage();">
                                                <i class="glyphicon glyphicon-trash"></i>
                                                <span>Xóa</span>
                                            </button>
                                            <input type="checkbox" class="toggle">
                                            <!-- The loading indicator is shown during file processing -->
                                            <span class="fileupload-loading"></span>
                                        </div>
                                        <!-- The global progress information -->
                                        <div class="col-lg-5 fileupload-progress fade">
                                            <!-- The global progress bar -->
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                                            </div>
                                            <!-- The extended global progress information -->
                                            <div class="progress-extended">&nbsp;</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                                }
                            ?>
                            <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
                            <div class="form-actions">
                            	<?php
									if($isEditMode){
                                ?>
                                		<?php
											$require_perm = array("edit promotion");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
			                                <button type="button" class="btn btn-primary" onclick="submitForm('fileupload', '../action/editDiscountAction.php', 'post');">Chỉnh sửa</button>
                                        <?php
											}
                                        ?>
                            	
                                <?php
									} else {
                                ?>
                                		<?php
											$require_perm = array("create promotion");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
                                			<button type="button" class="btn btn-primary" onclick="generateImageNames('imgPath');submitForm('fileupload', '../action/newDiscountAction.php', 'post');">Tạo mới</button>
                                        <?php
											}
                                        ?>
                                <?php
									}
                                ?>
                            </div>
                            	<input type="hidden" value="" id="imgPath" name="imgPath"/>
                            	<input type="hidden" value="<?php if($isEditMode) echo $disId; ?>" id="disId" name="disId"/>
                        </form>
                    </div><!--end of box content-->
                </div><!--end of box-->
            </div><!--end of content-->
        </div><!--end of row fluid-->
        <?php include("footer.php");?>
        <!-- The template to display files available for upload -->
		<script id="template-upload" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-upload fade">
                <td>
                    <span class="preview"></span>
                </td>
                <td>
                    <p class="name">{%=file.name%}</p>
                    {% if (file.error) { %}
                        <div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
                    <p class="size">{%=o.formatFileSize(file.size)%}</p>
                    {% if (!o.files.error) { %}
                        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
                    {% } %}
                </td>
                
                <td>
                    {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                        <button class="btn btn-primary start" style="visibility: hidden;">
                            <i class="glyphicon glyphicon-upload"></i>
                            <span>Bắt đầu</span>
                        </button>
                    {% } %}
                    {% if (!i) { %}
                        <button class="btn btn-warning cancel">
                            <i class="glyphicon glyphicon-ban-circle"></i>
                            <span>Hủy</span>
                        </button>
                    {% } %}
                </td>
            </tr>
        {% } %}
        </script>
        <!-- The template to display files available for download -->
        <script id="template-download" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-download fade">
                <td>
                    <span class="preview">
                        {% if (file.url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.url%}"></a>
                        {% } %}
                    </span>
                </td>
                <td>
                    <p class="name">
                        {% if (file.url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.url?'data-gallery':''%}>{%=file.name%}</a>
                        {% } else { %}
                            <span>{%=file.name%}</span>
                        {% } %}
                    </p>
                    {% if (file.error) { %}
                        <div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
                    <span class="size">{%=o.formatFileSize(file.size)%}</span>
                </td>
                <td>
                    <p class="name">
                        {% if (file.url) { %}
                                <span>{%=file.url%}</span>
                        {% } %}
                    </p>
                </td>
                <td>
                    {% if (file.deleteUrl) { %}
                        <button onclick="deleteImage();" class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                            <i class="glyphicon glyphicon-trash"></i>
                            <span>Xóa</span>
                        </button>
                        <input type="checkbox" name="delete" value="{%=file.name%}" class="toggle">
                    {% } else { %}
                        <button class="btn btn-warning cancel">
                            <i class="glyphicon glyphicon-ban-circle"></i>
                            <span>Hủy</span>
                        </button>
                    {% } %}
                </td>
            </tr>
        {% } %}
        </script>
    </div><!--end of container fluid-->
    <?php include("import-js.php");?>
    <?php include("import-js-upload.php");?>
    
    <script>
		$(document).ready(function() {
			$("#fileupload").validate({
                rules: {
                    name: { required: true },
                    value: { required: true }
                },
                
                messages: {
                    name: "<?php echo $messages["validation.required"];?>",
                    value: "<?php echo $messages["validation.required"];?>"
                }
            });
		});
		
		function deleteImage(){
            var dataString = "disId=" + $("#disId").val();
            $.ajax({
                type: "POST",
                url: "../action/ajax/deleteDiscountImageProcess.php",
                data: dataString
            });
        }
		
		function storeImage(){
			if($("#disId").val() != ""){
				var dataString = "imgPath=" + $("#imgPath").val() + "&id=" + $("#disId").val();
                $.ajax({
                    type: "POST",
                    url: "../action/ajax/storeDiscountImageProcess.php",
                    data: dataString,
                    success: function(data){}
                });
			}
		}
		
		var urls = "";
		// Initialize the jQuery File Upload widget:
		$('#fileupload').fileupload({
			url: '../image/',
			maxFileSize: <?php echo MAX_FILE_SIZE;?>,
			acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
		}).bind('fileuploadalways', function (e, data) {
			var fileName = extractFileNameFromFullPath(data.result.files);
			if(fileName != ""){
				$("#imgPath").val(fileName);
				storeImage();
			}
		});
    </script>
</body>
</html>